package net.wofly.common.interceptor;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

/**
 * @className: ${WebLogAspect}
 * @package: net.wofly.common.interceptor
 * @describe: 日志切面
 * @author: LiuJianbo
 * @date: 2018/1/6
 * @time: 17:40
 */
@Aspect
@Component
public class WebLogAspect {
    
    ThreadLocal<Long> startTime = new ThreadLocal<>();
    private Logger logger = LoggerFactory.getLogger(getClass());
    
    @Pointcut("execution(public * net.wofly.*.web..*.*(..)) || execution(public * net.wofly..*.web..*.*(..))")
    public void webLog() {
    }
    
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        startTime.set(System.currentTimeMillis());
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        logger.info(">>> -------------------------------------start--------------------------------------------");
        //获取请求sessionId
        logger.info(">>> sessionId:" + request.getRequestedSessionId());
        
        // 记录下请求内容
        logger.info(">>> URL : " + request.getRequestURL().toString());
        logger.info(">>> HTTP_METHOD : " + request.getMethod());
        logger.info(">>> 客户端IP : " + request.getRemoteAddr());
        logger.info(
                ">>> CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint
                        .getSignature().getName());
        logger.info(">>> 请求参数 : " + Arrays.toString(joinPoint.getArgs()));
        Object[] args = joinPoint.getArgs();
        if (null != args && args.length > 0) {
            for (int i = 0; i < args.length; i++) {
                if (!(args[i] instanceof HttpServletRequest) && ! (args[i] instanceof HttpServletResponse)) {
                    logger.info(">>> 请求参数 [{}] : {}", i + 1, JSON.toJSONString(args[i]));
                }
            }
        }
        
        //logger.info(">>> 请求参数：" + JSON.toJSONString(request.getParameterMap(),
        //        SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteMapNullValue));
    }
    
    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        //请求错误码
        logger.info(">>> 返回数据 : " + JSON.toJSONString(ret));
        logger.info(">>> 请求耗时 : " + (System.currentTimeMillis() - startTime.get()));
        logger.info(">>> ------------------------------------- end --------------------------------------------");
    }
    
}
